package com.imflea.zero.config;

import com.baomidou.mybatisplus.annotation.FieldStrategy;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;


@Configuration

@MapperScan(basePackages = {"com.imflea.zero.model.dao",}, sqlSessionFactoryRef = "sqlSessionFactory")
public class MybatisConfig {
    @Autowired
    private DruidConfig dataSource;
    @Autowired
    private MetaHandler metaHandler;

    private static String LOCAL_MAPPER = "classpath*:mapper/**/*Mapper.xml";


//    @Bean
//    public Interceptor paginationInterceptor() {
//
//        return new PaginationInterceptor();
//
//    }

    @Primary
    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory masterSqlSessionFactory() throws Exception {
        MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource.getDataSource());
        //处理全局配置
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setMetaObjectHandler(metaHandler);
//        globalConfig.setSqlInjector()

        //全局配置中的数据配置
        GlobalConfig.DbConfig dbConfig = new GlobalConfig.DbConfig();
        dbConfig.setIdType(IdType.ASSIGN_UUID);
        dbConfig.setSelectStrategy(FieldStrategy.NOT_NULL);
        dbConfig.setInsertStrategy(FieldStrategy.NOT_NULL);
        dbConfig.setUpdateStrategy(FieldStrategy.NOT_NULL);
        dbConfig.setCapitalMode(true);
        dbConfig.setTableUnderline(true);
        dbConfig.setLogicDeleteField("delFlag");
        dbConfig.setLogicDeleteValue("1");
        dbConfig.setLogicNotDeleteValue("0");
        globalConfig.setDbConfig(dbConfig);

        //全局配置中的数据配置完成

        factoryBean.setGlobalConfig(globalConfig);

        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(LOCAL_MAPPER));
        //手动设置session工厂时，需要手动添加分页插件
        Interceptor[] plugins = new Interceptor[1];
//        plugins[0] = paginationInterceptor();
//        factoryBean.setPlugins(plugins);
        //开启驼峰转换
        SqlSessionFactory sqlSessionFactory = factoryBean.getObject();
        org.apache.ibatis.session.Configuration configuration = sqlSessionFactory.getConfiguration();
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setLogImpl(StdOutImpl.class);
        return factoryBean.getObject();
    }

}
